Page({
  data: {
    raceTime: '',
    raceTimeDisplay: '',
    raceLocation: '',
    showTimeModal: false,
    years: [],
    months: [],
    days: [],
    datePickerValue: [0, 0, 0],
    startTime: '16:00',
    endTime: '18:00',
    signupList: [null, null, null, null, null, null, null, null],
    signupCount: 0,
    showSignupAction: false,
    signupIndex: -1,
    showMatchModal: false,
    girlSetting: 'standard',
    matchCount: 9,
    matchList: [],
    disclaimerChecked: true,
    selectedItemIndex: 0,
    scoreModalVisible: false,
    scoreModalIndex: -1,
    scoreLeft: '',
    scoreRight: '',
    scoreModalLeft: [],
    scoreModalRight: [],
    resultList: [],
    userInfo: null,
    courtCount: 1,
    maxCourtCount: 1,
    safePaddingTop: 0,
    showGenderSelect: false,
    tempOtherName: '',
    tempOtherGender: 'male',
    showEditTitleModal: false,
    editTitleValue: '',
    raceTitle: '',
    defaultRaceTitle: '固搭循环赛 | 7-3发布',
    showOtherSignupModal: false,
    finishedCount: 0,
    scoreTabIndex: 0,
    scoreTabList: [
      { title: '全部', count: 0 },
      { title: '未结束', count: 0 },
      { title: '可以比赛', count: 0 },
      { title: '比赛中', count: 0 }
    ],
    filteredMatchList: [],
    showRegenMatchBtn: false,
    maxPlayers: 8,
    appliedCount: 0,
    roundType: 'single', // 比赛循环次数：single-单循环，double-自定义
    customRoundCount: 3, // 自定义循环次数
    showQuickSignupModal: false,
    quickSignupText: '',
    quickSignupPreviewPages: [],
    quickSignupPreviewPageIndex: 0,
    quickSignupPreviewPageSize: 15,
    editSignupIndex: -1, // 新增：编辑报名时记录索引
    editSignupName: '', // 新增：编辑报名时记录昵称
    editSignupGender: 'male', // 新增：编辑报名时记录性别
    showEditSignupModal: false, // 新增：编辑报名弹窗是否显示
    modalOpen: false, // 防止多次弹窗
    raceInfo: null,
    isCreator: false, // 是否为创建人
    partnerGroups: [], // 搭档组信息
    scoreModalVisible: false, // 计分弹窗是否显示
    currentScoreIndex: -1, // 当前正在计分的比赛索引
    leftScore: '', // 左方比分
    rightScore: '', // 右方比分

    stageTabCodes: [], // 阶段标签代码
    bracketColumns: [], // 淘汰赛列数据
    thirdPlaceMatch: null, // 第三名比赛数据
    thirdPlaceMatchIndex: -1, // 第三名比赛在matchList中的索引
    resultTabIndex: 0, // 成绩标签页索引：0-总排名，1-循环赛排名
    resultTabList: [
      { title: '总排名' },
      { title: '循环赛排名' }
    ],
    roundRobinResultList: [], // 循环赛排名数据
  },
  onLoad(options) {
    if (!options.id) {
      wx.showToast({ title: '缺少比赛ID', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
      return;
    }
    this.options = options;
    this.raceId = options.id;
    
    // 引入本地数据管理器
    const localDataManager = require('../../utils/localDataManager.js');
    this.localDataManager = localDataManager;
    
    // 获取系统状态栏和导航栏高度
    wx.getWindowInfo({
      success: res => {
        const statusBarHeight = res.statusBarHeight || 20;
        const navBarHeight = 44; // 可根据实际微调
        this.setData({
          safePaddingTop: statusBarHeight + navBarHeight
        });
      }
    });
    
    // 从本地存储加载比赛基本信息
    const raceId = options.id;
    const raceData = localDataManager.getRace(raceId);
    
    if (raceData) {
      let selectedItemIndex = 0;
      let showRegenMatchBtn = false;
      if (raceData.status === '计分中') {
        selectedItemIndex = 1;
        showRegenMatchBtn = true;
      } else if (raceData.status === '已完赛') {
        selectedItemIndex = 2;
        showRegenMatchBtn = true;
      }
      
      // 判断是否为创建人
      const app = getApp();
      const currentUser = app.globalData.userInfo;
      const isCreator = currentUser && raceData.creator && 
                       (currentUser.userId === raceData.creator.userId || 
                        currentUser.phone === raceData.creator.phone);
      
      this.setData({
        raceTitle: raceData.title || '',
        raceTimeDisplay: raceData.dateStr || '',
        raceLocation: raceData.location || '',
        selectedItemIndex,
        showRegenMatchBtn,
        maxPlayers: raceData.maxPlayers || 8,
        courtCount: raceData.courtCount || 1,
        isCreator: isCreator,
        raceInfo: {
          name: raceData.title || '',
          dateStr: raceData.dateStr || '',
          location: raceData.location || '',
          totalNum: raceData.maxPlayers || 8
        }
      }, () => {
        this.loadSignupList();
      });
    } else {
      // 如果比赛不存在，设置默认值并显示报名框
      this.setData({
        maxPlayers: 8,
        signupList: [null, null, null, null, null, null, null, null],
        signupCount: 0
      }, () => {
        this.loadSignupList();
      });

    }
    const date = new Date();
    const years = [];
    for (let i = date.getFullYear(); i <= date.getFullYear() + 2; i++) years.push(i);
    const months = [];
    for (let i = 1; i <= 12; i++) months.push(i);
    const days = this.getDaysInMonth(date.getFullYear(), date.getMonth() + 1);
    const datePickerValue = [0, date.getMonth(), date.getDate() - 1];
    this.setData({ years, months, days, datePickerValue, signupCount: 0 });
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({ userInfo: app.globalData.userInfo });
    }
    this.updateCourtCountLimit();
    this.loadMatchList();
    
  },

  getDaysInMonth(year, month) {
    const days = [];
    const dayCount = new Date(year, month, 0).getDate();
    for (let i = 1; i <= dayCount; i++) days.push(i);
    return days;
  },
  onEditTime() {
    if (!this.data.isCreator) {
      wx.showToast({ title: '只有创建人才能修改', icon: 'none' });
      return;
    }
    this.setData({ showTimeModal: true });
  },
  onCloseTimeModal() {
    this.setData({ showTimeModal: false });
  },
  onDateChange(e) {
    const { years, months } = this.data;
    const [yearIdx, monthIdx, dayIdx] = e.detail.value;
    const year = years[yearIdx];
    const month = months[monthIdx];
    const days = this.getDaysInMonth(year, month);
    let newDayIdx = dayIdx;
    if (dayIdx >= days.length) newDayIdx = days.length - 1;
    this.setData({
      datePickerValue: [yearIdx, monthIdx, newDayIdx],
      days
    });
  },
  onStartTimeChange(e) {
    this.setData({ startTime: e.detail.value });
  },
  onEndTimeChange(e) {
    this.setData({ endTime: e.detail.value });
  },
  onConfirmTime() {
    const { years, months, days, datePickerValue, startTime, endTime } = this.data;
    const year = years[datePickerValue[0]];
    const month = months[datePickerValue[1]];
    const day = days[datePickerValue[2]];
    const dateStr = `${year}-${month < 10 ? '0'+month : month}-${day < 10 ? '0'+day : day}`;
    const display = `${dateStr} ${startTime} 至 ${endTime}`;
    const raceId = this.options && this.options.id;

    // 更新本地存储中的比赛信息
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) {
      raceData.dateStr = display;
      this.localDataManager.saveRace(raceData);
      
      wx.showToast({ title: '时间已更新' });
      this.setData({
        raceTime: `${dateStr} ${startTime}-${endTime}`,
        raceTimeDisplay: display,
        showTimeModal: false
      });
    } else {
      wx.showToast({ title: '比赛不存在', icon: 'none' });
    }
  },
  onEditLocation() {
    if (!this.data.isCreator) {
      wx.showToast({ title: '只有创建人才能修改', icon: 'none' });
      return;
    }
    
    wx.showModal({
      title: '编辑比赛地点',
      content: this.data.raceLocation || '',
      placeholderText: '请输入比赛地点',
      editable: true,
      success: (res) => {
        if (res.confirm && res.content) {
          const newLocation = res.content.trim();
          if (newLocation) {
            this.setData({
              raceLocation: newLocation
            });
            
            // 更新比赛信息
            const raceData = this.localDataManager.getRace(this.raceId);
            if (raceData) {
              raceData.location = newLocation;
              this.localDataManager.saveRace(raceData);
            }
            
            wx.showToast({ title: '地点修改成功', icon: 'success' });
          }
        }
      }
    });
  },
  // ======= 登录授权统一处理 =======
  ensureLogin(callback) {
    let userInfo = this.data.userInfo || getApp().globalData.userInfo;
    if (userInfo) {
      if (typeof callback === 'function') callback();
      return;
    }
    wx.showModal({
      title: '温馨提示',
      content: '你还未登录，请登录后再进行操作',
      confirmText: '登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.getUserProfile({
            desc: '用于完善会员资料',
            success: res => {
              getApp().globalData.userInfo = res.userInfo;
              this.setData({ userInfo: res.userInfo });
              wx.showToast({ title: '登录成功', icon: 'success' });
              if (typeof callback === 'function') callback();
            },
            fail: err => {
              wx.showToast({ title: '微信授权失败', icon: 'none' });
            }
          });
        }
        // 取消时什么都不做
      }
    });
  },
  onSignupTap(e) {
    const index = e.currentTarget.dataset.index;
    const { signupList } = this.data;
    this.ensureLogin(() => {
      let currentUser = this.data.userInfo || getApp().globalData.userInfo;
      const item = signupList[index];
      
      // 检查当前用户是否已经报名
      const signupDataList = this.localDataManager.getSignups(this.raceId);
      const hasSigned = signupDataList && signupDataList.some(signup => 
        signup.userInfo && signup.userInfo.nickName === currentUser.nickName
      );
      
      if (!item || !item.nickName || !item._id) {
        // 空位：显示报名选项，如果用户已报名则隐藏"本人报名"选项
        this.setData({ showSignupAction: true, signupIndex: index, hasSigned: hasSigned });
        return;
      }
      
      // 检查是否是当前用户的报名
      const isCurrentUserSignup = item.nickName === currentUser.nickName;
      
      if (isCurrentUserSignup) {
        // 当前用户的报名：显示编辑/取消选项
        wx.showActionSheet({
          itemList: ['编辑', '取消报名'],
          success: (res) => {
            if (res.tapIndex === 0) {
              this.setData({
                editSignupIndex: index,
                editSignupName: item.nickName,
                editSignupGender: item.gender || 'male',
                showEditSignupModal: true
              });
            } else if (res.tapIndex === 1) {
              wx.showModal({
                title: '取消报名',
                content: '确定要取消该报名吗？',
                confirmText: '取消报名',
                cancelText: '关闭',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    const raceId = this.options && this.options.id;
                    
                    // 从本地存储中删除报名
                    this.localDataManager.removeSignup(raceId, item._id);
                    wx.showToast({ title: '已取消报名' });
                    
                    // 更新比赛信息
                    const raceData = this.localDataManager.getRace(raceId);
                    if (raceData) {
                      raceData.courtCount = this.data.courtCount;
                      this.localDataManager.saveRace(raceData);
                    }
                    
                    this.loadSignupList();
                  }
                }
              });
            }
          }
        });
      } else {
        // 其他人的报名：允许编辑（移除限制）
        wx.showActionSheet({
          itemList: ['编辑', '取消报名'],
          success: (res) => {
            if (res.tapIndex === 0) {
              this.setData({
                editSignupIndex: index,
                editSignupName: item.nickName,
                editSignupGender: item.gender || 'male',
                showEditSignupModal: true
              });
            } else if (res.tapIndex === 1) {
              wx.showModal({
                title: '取消报名',
                content: '确定要取消该报名吗？',
                confirmText: '取消报名',
                cancelText: '关闭',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    const raceId = this.options && this.options.id;
                    
                    // 从本地存储中删除报名
                    this.localDataManager.removeSignup(raceId, item._id);
                    wx.showToast({ title: '已取消报名' });
                    
                    // 更新比赛信息
                    const raceData = this.localDataManager.getRace(raceId);
                    if (raceData) {
                      raceData.courtCount = this.data.courtCount;
                      this.localDataManager.saveRace(raceData);
                    }
                    
                    this.loadSignupList();
                  }
                }
              });
            }
          }
        });
      }
    });
  },
  onCloseSignupAction() {
    this.setData({ showSignupAction: false, signupIndex: -1 });
  },
  updateSignupCount() {
    const count = this.data.signupList.filter(item => item).length;
    this.setData({ signupCount: count });
    this.updateCourtCountLimit();
  },
  onSignupSelf() {
    this.ensureLogin(() => {
      let userInfo = this.data.userInfo || getApp().globalData.userInfo;
      const { signupIndex } = this.data;
      const raceId = this.options && this.options.id;
      
      // 检查用户是否已经报名
      const signupDataList = this.localDataManager.getSignups(raceId);
      const hasSigned = signupDataList && signupDataList.some(signup => 
        signup.userInfo && signup.userInfo.nickName === userInfo.nickName
      );
      
      if (hasSigned) {
        wx.showToast({ 
          title: '您已报名，不能重复报名', 
          icon: 'none',
          duration: 2000
        });
        this.setData({ showSignupAction: false, signupIndex: -1 });
        return;
      }
      
      // 兼容微信用户信息的 gender 字段（1男2女0未知）和字符串格式
      let gender = 'male';
      if (userInfo.gender === 2 || userInfo.gender === 'female') {
        gender = 'female';
      } else if (userInfo.gender === 1 || userInfo.gender === 'male') {
        gender = 'male';
      } else {
        // 如果性别未知，默认为男性
        gender = 'male';
      }
      
      // 根据性别设置头像
      let avatarUrl = userInfo.avatarUrl;
      if (gender === 'female') {
        avatarUrl = '../../images/avatar_girl.png';
      } else if (gender === 'male') {
        avatarUrl = '../../images/avatar_boy.png';
      }
      
      // Use the clicked position as order, maintaining position
      const order = signupIndex;
      
      // 添加到本地存储
      const signupData = {
        raceId,
        order: order,
        userInfo: {
          nickName: userInfo.nickName,
          avatarUrl: avatarUrl,
          gender: gender
        }
      };
      
      const success = this.localDataManager.addSignup(raceId, signupData);
      if (success) {
        wx.showToast({ title: '报名成功', icon: 'success' });
        
        // 更新比赛信息
        const raceData = this.localDataManager.getRace(raceId);
        if (raceData) {
          raceData.courtCount = this.data.courtCount;
          this.localDataManager.saveRace(raceData);
        }
        
        this.setData({ showSignupAction: false, signupIndex: -1 }, () => {
          this.loadSignupList();
        });
      } else {
        wx.showToast({ title: '报名失败', icon: 'none' });
      }
    });
  },
  onSignupOther() {
    this.setData({
      showOtherSignupModal: true,
      tempOtherName: '',
      tempOtherGender: 'male'
    });
  },
  onOtherNameInput(e) {
    this.setData({
      tempOtherName: e.detail.value
    });
  },
  onSelectGender(e) {
    this.setData({
      tempOtherGender: e.currentTarget.dataset.gender
    });
  },
  onConfirmOtherSignup() {
    const { signupIndex, tempOtherName, tempOtherGender } = this.data;
    if (!tempOtherName.trim()) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    const raceId = this.options && this.options.id;
    
    // 检查是否已经存在相同姓名的报名
    const signupDataList = this.localDataManager.getSignups(raceId);
    const hasSigned = signupDataList && signupDataList.some(signup => 
      signup.userInfo && signup.userInfo.nickName === tempOtherName
    );
    
    if (hasSigned) {
      wx.showToast({ 
        title: '该选手已报名，不能重复报名', 
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    let avatarUrl = '../../images/avatar_boy.png';
    if (tempOtherGender === 'female') {
      avatarUrl = '../../images/avatar_girl.png';
    }
    
    // Use the clicked position as order, maintaining position
    const order = signupIndex;
    
    // 添加到本地存储
    const signupData = {
      raceId,
      order: order,
      userInfo: {
        nickName: tempOtherName,
        avatarUrl: avatarUrl,
        gender: tempOtherGender
      }
    };
    
    const success = this.localDataManager.addSignup(raceId, signupData);
    
    if (success) {
      wx.showToast({ title: '报名成功', icon: 'success' });
      
      // 更新比赛信息
      const raceData = this.localDataManager.getRace(raceId);
      if (raceData) {
        raceData.courtCount = this.data.courtCount;
        this.localDataManager.saveRace(raceData);
      }
      
      this.setData({
        showOtherSignupModal: false,
        showSignupAction: false,
        signupIndex: -1,
        tempOtherName: '',
        tempOtherGender: 'male'
      }, () => {
        this.loadSignupList();
      });
    } else {
      wx.showToast({ title: '报名失败', icon: 'none' });
    }
  },
  onCancelOtherSignup() {
    this.setData({
      showOtherSignupModal: false,
      showSignupAction: false,
      signupIndex: -1,
      tempOtherName: '',
      tempOtherGender: 'male'
    });
  },
  onAddGroup() {
    // 一次增加一组（2人）
    let maxPlayers = this.data.maxPlayers;
    if (maxPlayers >= 32) {
      wx.showToast({ title: '已达16组上限', icon: 'none' });
      return;
    }
    maxPlayers += 2; // 增加一组（2人）
    let signupList = (this.data.signupList || []).slice();
    while (signupList.length < maxPlayers) signupList.push(null);
    this.setData({ maxPlayers, signupList }, () => { 
      this.updatePartnerGroups();
      this.updateSignupCount(); // 更新报名计数
    });
    const raceId = this.options && this.options.id;
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) { raceData.maxPlayers = maxPlayers; this.localDataManager.saveRace(raceData); }
    wx.showToast({ title: `已增加至${maxPlayers/2}组`, icon: 'success' });
  },
  onRemoveGroup() {
    // 一次减少一组（2人）
    let maxPlayers = this.data.maxPlayers;
    if (maxPlayers <= 8) {
      wx.showToast({ title: '最少4组', icon: 'none' });
      return;
    }
    maxPlayers -= 2; // 减少一组（2人）
    
    // 获取报名数据
    const raceId = this.options && this.options.id;
    const signupDataList = this.localDataManager.getSignups(raceId) || [];
    
    // 找出order小于新maxPlayers的报名数据并保留
    const filteredSignups = signupDataList.filter(signup => signup.order < maxPlayers);
    
    // 更新本地存储
    this.localDataManager.clearSignups(raceId);
    filteredSignups.forEach(signup => {
      this.localDataManager.addSignup(raceId, signup);
    });
    
    let signupList = (this.data.signupList || []).slice(0, maxPlayers);
    this.setData({ maxPlayers, signupList }, () => { 
      this.updatePartnerGroups();
      this.updateSignupCount(); // 更新报名计数
    });
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) { raceData.maxPlayers = maxPlayers; this.localDataManager.saveRace(raceData); }
    wx.showToast({ title: `已减少至${maxPlayers/2}组`, icon: 'success' });
  },

  onOpenDisclaimer() {
    wx.navigateTo({ url: '/pages/disclaimer/disclaimer' });
  },
  // 公平轮换分组算法，参考多人轮转赛的算法，确保搭档组比赛次数均匀
  generateFairRotation(players, totalMatches, courts) {
    // 在固搭循环赛中，players是个人，但我们需要按搭档组来生成对阵
    const n = players.length;
    const groupCount = players.length / 2; // 正确计算双打组数
    
    // 将个人按搭档组重新组织
    const partnerGroups = [];
    for (let i = 0; i < players.length; i += 2) {
      const player1 = players[i];
      const player2 = players[i + 1];
      if (player1 && player2) {
        partnerGroups.push([player1, player2]);
      }
    }
    
    // 记录每个搭档组的比赛次数
    let groupPlayCount = Array(groupCount).fill(0);
    let matchList = [];
    let round = 0;
    
    // 计算每个搭档组应该参赛的次数（理想情况下）
    const totalGroupSlots = totalMatches * 2; // 每场比赛2个搭档组
    const avgMatchesPerGroup = Math.floor(totalGroupSlots / groupCount);
    const extraSlots = totalGroupSlots % groupCount;
    
    // 为每个搭档组分配目标参赛次数
    let targetMatches = Array(groupCount).fill(avgMatchesPerGroup);
    for (let i = 0; i < extraSlots; i++) {
      targetMatches[i]++;
    }
    
    // 生成比赛
    while (matchList.length < totalMatches) {
      // 为每个场地生成比赛
      for (let c = 0; c < courts; c++) {
        if (matchList.length >= totalMatches) break;
        
        // 选择参赛次数最接近目标且最少的搭档组
        let availableGroups = groupPlayCount.map((cnt, idx) => ({
          cnt,
          idx,
          target: targetMatches[idx],
          deficit: targetMatches[idx] - cnt // 还差多少场
        }))
        .filter(g => g.deficit > 0) // 只选择还没达到目标的人
        .sort((a, b) => {
          // 优先选择还差场次最多的搭档组
          if (a.deficit !== b.deficit) return b.deficit - a.deficit;
          // 其次选择当前参赛次数最少的搭档组
          if (a.cnt !== b.cnt) return a.cnt - b.cnt;
          // 最后随机排序
          return Math.random() - 0.5;
        });
        
        // 确保有足够的搭档组
        if (availableGroups.length < 2) {
          // 如果不够2个搭档组，从所有搭档组中选择参赛次数最少的
          availableGroups = groupPlayCount.map((cnt, idx) => ({cnt, idx}))
            .sort((a, b) => a.cnt - b.cnt || Math.random() - 0.5);
        }
        
        // 选择前2个搭档组
        const selectedIndices = availableGroups.slice(0, 2).map(g => g.idx);
        
        // 创建比赛
        const match = {
          left: partnerGroups[selectedIndices[0]],
          right: partnerGroups[selectedIndices[1]],
          status: 'ready',
          round: round + 1,
          courtIndex: c
        };
        
        // 确保比赛有效
        if (match.left && match.right) {
          matchList.push(match);
          
          // 增加参赛次数
          selectedIndices.forEach(idx => {
            if (idx !== undefined && idx < groupCount) {
              groupPlayCount[idx]++;
            }
          });
        }
      }
      round++;
      
      // 防止无限循环
      if (round > totalMatches * 3) break;
    }
    
    return matchList.slice(0, totalMatches);
  },
  // 新增：4强单败淘汰赛对阵生成（半决赛→决赛）
  generateFourTeamElimination(partnerGroups) {
    // partnerGroups: Array<[p1,p2]> length should be 4
    const seedGroups = partnerGroups.slice(0, 4);
    const placeholder = () => ({ nickName: '待定', avatarUrl: '../../images/avatar_boy.png', gender: 'male' });
    const courtCount = this.data.courtCount || 1; // 使用用户设置的场地数，默认为1

    // 建立4场比赛：2场半决赛(SF1-2)，1场决赛(F1)，1场第三名决赛(TP1)
    const matches = [];

    // SF1: 1 vs 4
    matches.push({
      id: 'SF1', stage: 'SF', stageOrder: 1, stageName: '半决赛', position: 1,
      left: seedGroups[0] || [placeholder(), placeholder()],
      right: seedGroups[3] || [placeholder(), placeholder()],
      status: 'ready', courtIndex: 0 % courtCount, round: 1, nextMatchId: 'F1', nextMatchSide: 'left'
    });
    // SF2: 2 vs 3
    matches.push({
      id: 'SF2', stage: 'SF', stageOrder: 1, stageName: '半决赛', position: 2,
      left: seedGroups[1] || [placeholder(), placeholder()],
      right: seedGroups[2] || [placeholder(), placeholder()],
      status: 'ready', courtIndex: 1 % courtCount, round: 1, nextMatchId: 'F1', nextMatchSide: 'right'
    });

    // 第三名决赛：半决赛败者对决
    matches.push({
      id: 'TP1', stage: 'TP', stageOrder: 3, stageName: '第三名决赛', position: 1,
      left: [placeholder(), placeholder()], right: [placeholder(), placeholder()],
      status: 'pending', courtIndex: 0, round: 3
    });

    // Final winners of SF1/SF2
    matches.push({
      id: 'F1', stage: 'F', stageOrder: 4, stageName: '决赛', position: 1,
      left: [placeholder(), placeholder()], right: [placeholder(), placeholder()],
      status: 'ready', courtIndex: 0, round: 4
    });

    return matches;
  },
  // 新增：循环赛制，用于非4倍数小组的情况
  generateRoundRobin(partnerGroups, advancingCount) {
    const matches = [];
    const placeholder = () => ({ nickName: '待定', avatarUrl: '../../images/avatar_boy.png', gender: 'male' });
    
    // 记录每个搭档组的比赛次数和最近比赛轮次
    const groupPlayCount = Array(partnerGroups.length).fill(0);
    const lastRoundPlayed = Array(partnerGroups.length).fill(-1);
    
    // 收集所有可能的比赛
    const allMatches = [];
    for (let i = 0; i < partnerGroups.length; i++) {
      for (let j = i + 1; j < partnerGroups.length; j++) {
        allMatches.push({
          id: `RR_${i+1}_${j+1}`,
          stage: 'RR',
          stageOrder: 1,
          stageName: '循环赛',
          position: allMatches.length + 1,
          left: partnerGroups[i],
          right: partnerGroups[j],
          groupIndices: [i, j]
        });
      }
    }
    
    // 使用类似固搭页面的公平轮换算法
    const totalMatches = allMatches.length;
    const courts = this.data.courtCount || 1; // 使用用户设置的场地数，默认为1
    let round = 0;
    
    // 计算每个搭档组应该参赛的次数（理想情况下）
    const totalGroupSlots = totalMatches * 2; // 每场比赛2个搭档组
    const groupCount = partnerGroups.length;
    const avgMatchesPerGroup = Math.floor(totalGroupSlots / groupCount);
    const extraSlots = totalGroupSlots % groupCount;
    
    // 为每个搭档组分配目标参赛次数
    let targetMatches = Array(groupCount).fill(avgMatchesPerGroup);
    for (let i = 0; i < extraSlots; i++) {
      targetMatches[i]++;
    }
    
    // 生成比赛
    while (matches.length < totalMatches && allMatches.length > 0) {
      // 为每个场地生成比赛
      for (let c = 0; c < courts; c++) {
        if (matches.length >= totalMatches || allMatches.length === 0) break;
        
        // 选择参赛次数最接近目标且最少的搭档组的比赛
        let availableMatches = allMatches.map(match => {
          const [idx1, idx2] = match.groupIndices;
          const deficit1 = targetMatches[idx1] - groupPlayCount[idx1];
          const deficit2 = targetMatches[idx2] - groupPlayCount[idx2];
          const totalDeficit = deficit1 + deficit2;
          const totalPlayCount = groupPlayCount[idx1] + groupPlayCount[idx2];
          
          return {
            match,
            deficit: totalDeficit,
            playCount: totalPlayCount,
            lastRound: Math.max(lastRoundPlayed[idx1], lastRoundPlayed[idx2])
          };
        })
        .filter(m => m.deficit > 0) // 只选择还没达到目标的比赛
        .sort((a, b) => {
          // 优先选择还差场次最多的比赛
          if (a.deficit !== b.deficit) return b.deficit - a.deficit;
          // 其次选择当前参赛次数最少的比赛
          if (a.playCount !== b.playCount) return a.playCount - b.playCount;
          // 最后选择最近比赛轮次较早的比赛
          if (a.lastRound !== b.lastRound) return a.lastRound - b.lastRound;
          // 最后随机排序
          return Math.random() - 0.5;
        });
        
        // 如果没有符合条件的比赛，从所有比赛中选择参赛次数最少的
        if (availableMatches.length === 0) {
          availableMatches = allMatches.map(match => {
            const [idx1, idx2] = match.groupIndices;
            const totalPlayCount = groupPlayCount[idx1] + groupPlayCount[idx2];
            const lastRound = Math.max(lastRoundPlayed[idx1], lastRoundPlayed[idx2]);
            
            return {
              match,
              playCount: totalPlayCount,
              lastRound: lastRound
            };
          })
          .sort((a, b) => {
            // 优先选择当前参赛次数最少的比赛
            if (a.playCount !== b.playCount) return a.playCount - b.playCount;
            // 其次选择最近比赛轮次较早的比赛
            if (a.lastRound !== b.lastRound) return a.lastRound - b.lastRound;
            // 最后随机排序
            return Math.random() - 0.5;
          });
        }
        
        // 选择最合适的比赛
        const selectedMatch = availableMatches[0].match;
        
        // 从候选列表中移除已选择的比赛
        const matchIndex = allMatches.findIndex(m => m.id === selectedMatch.id);
        if (matchIndex !== -1) {
          allMatches.splice(matchIndex, 1);
        }
        
        // 添加到比赛列表
        matches.push({
          ...selectedMatch,
          status: 'ready',
          courtIndex: c,
          round: round + 1
        });
        
        // 更新参赛者的比赛次数和最近比赛轮次
        const [idx1, idx2] = selectedMatch.groupIndices;
        groupPlayCount[idx1]++;
        groupPlayCount[idx2]++;
        lastRoundPlayed[idx1] = round + 1;
        lastRoundPlayed[idx2] = round + 1;
      }
      round++;
      
      // 防止无限循环
      if (round > totalMatches * 3) break;
    }
    
    // 根据晋级数量生成淘汰赛
    if (advancingCount === 8) {
      // 生成8强淘汰赛
      const quarterFinalMatches = [
        { id: 'QF1', position: 1, nextMatchId: 'SF1', nextMatchSide: 'left' },
        { id: 'QF2', position: 2, nextMatchId: 'SF1', nextMatchSide: 'right' },
        { id: 'QF3', position: 3, nextMatchId: 'SF2', nextMatchSide: 'left' },
        { id: 'QF4', position: 4, nextMatchId: 'SF2', nextMatchSide: 'right' }
      ];
      
      quarterFinalMatches.forEach((match, qfIndex) => {
        matches.push({
          id: match.id,
          stage: 'QF',
          stageOrder: 2,
          stageName: '四分之一决赛',
          position: match.position,
          left: [placeholder(), placeholder()],
          right: [placeholder(), placeholder()],
          status: 'ready',
          courtIndex: qfIndex % 4, // 4个场地
          round: Math.ceil(matches.length / 2) + 1, // 下一轮
          nextMatchId: match.nextMatchId,
          nextMatchSide: match.nextMatchSide
        });
      });
      
      // 半决赛
      matches.push({
        id: 'SF1',
        stage: 'SF',
        stageOrder: 3,
        stageName: '半决赛',
        position: 1,
        left: [placeholder(), placeholder()],
        right: [placeholder(), placeholder()],
        status: 'ready',
        courtIndex: 0,
        round: Math.ceil(matches.length / 4) + 2, // 再下一轮
        nextMatchId: 'F1',
        nextMatchSide: 'left'
      });
      
      matches.push({
        id: 'SF2',
        stage: 'SF',
        stageOrder: 3,
        stageName: '半决赛',
        position: 2,
        left: [placeholder(), placeholder()],
        right: [placeholder(), placeholder()],
        status: 'ready',
        courtIndex: 1,
        round: Math.ceil(matches.length / 4) + 2, // 再下一轮
        nextMatchId: 'F1',
        nextMatchSide: 'right'
      });
    } else if (advancingCount === 4) {
      // 生成4强淘汰赛（直接半决赛）
      matches.push({
        id: 'SF1',
        stage: 'SF',
        stageOrder: 2,
        stageName: '半决赛',
        position: 1,
        left: [placeholder(), placeholder()],
        right: [placeholder(), placeholder()],
        status: 'ready',
        courtIndex: 0,
        round: Math.ceil(matches.length / 2) + 1, // 下一轮
        nextMatchId: 'F1',
        nextMatchSide: 'left'
      });
      
      matches.push({
        id: 'SF2',
        stage: 'SF',
        stageOrder: 2,
        stageName: '半决赛',
        position: 2,
        left: [placeholder(), placeholder()],
        right: [placeholder(), placeholder()],
        status: 'ready',
        courtIndex: 1,
        round: Math.ceil(matches.length / 2) + 1, // 下一轮
        nextMatchId: 'F1',
        nextMatchSide: 'right'
      });
    }
    
    // 第三名比赛
    matches.push({
      id: 'TP1',
      stage: 'TP',
      stageOrder: advancingCount === 8 ? 4 : 3,
      stageName: '第三名决赛',
      position: 1,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'ready',
      courtIndex: 0,
      round: advancingCount === 8 ? Math.ceil(matches.length / 4) + 3 : Math.ceil(matches.length / 2) + 2 // 再下一轮
    });

    // 决赛
    matches.push({
      id: 'F1',
      stage: 'F',
      stageOrder: advancingCount === 8 ? 5 : 4,
      stageName: '决赛',
      position: 1,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'ready',
      courtIndex: 0,
      round: advancingCount === 8 ? Math.ceil(matches.length / 4) + 4 : Math.ceil(matches.length / 2) + 3 // 最后一轮
    });
    
    return matches;
  },
  
  // 新增：8组直接配对赛制（第一组vs第二组，第三组vs第四组，以此类推）
  generateEightGroupElimination(partnerGroups) {
    const matches = [];
    const placeholder = () => ({ nickName: '待定', avatarUrl: '../../images/avatar_boy.png', gender: 'male' });
    const courtCount = this.data.courtCount || 1; // 使用用户设置的场地数，默认为1
    
    // 8组直接配对，共4场比赛
    for (let i = 0; i < 4; i++) {
      const team1Index = i * 2;
      const team2Index = i * 2 + 1;
      
      matches.push({
        id: `M${i + 1}`,
        stage: 'QF',
        stageOrder: 1,
        stageName: '四分之一决赛',
        position: i + 1,
        left: partnerGroups[team1Index],
        right: partnerGroups[team2Index],
        status: 'ready',
        courtIndex: i % courtCount, // 使用用户设置的场地数
        round: 1,
        nextMatchId: i < 2 ? 'SF1' : 'SF2',
        nextMatchSide: i % 2 === 0 ? 'left' : 'right'
      });
    }
    
    // 半决赛：四分之一决赛胜者对决
    matches.push({
      id: 'SF1',
      stage: 'SF',
      stageOrder: 2,
      stageName: '半决赛',
      position: 1,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'ready',
      courtIndex: 0,
      round: 2, // 下一轮
      nextMatchId: 'F1',
      nextMatchSide: 'left'
    });
    
    matches.push({
      id: 'SF2',
      stage: 'SF',
      stageOrder: 2,
      stageName: '半决赛',
      position: 2,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'ready',
      courtIndex: 1,
      round: 2, // 下一轮
      nextMatchId: 'F1',
      nextMatchSide: 'right'
    });
    
    // 第三名比赛
    matches.push({
      id: 'TP1',
      stage: 'TP',
      stageOrder: 3,
      stageName: '第三名决赛',
      position: 1,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'pending',
      courtIndex: 0,
      round: 3 // 再下一轮
    });

    // 决赛
    matches.push({
      id: 'F1',
      stage: 'F',
      stageOrder: 4,
      stageName: '决赛',
      position: 1,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'ready',
      courtIndex: 0,
      round: 4 // 最后一轮
    });
    
    return matches;
  },
  
  // 新增：12组和16组直接配对赛制（第一组vs第二组，第三组vs第四组，以此类推）
  generateFourGroupElimination(partnerGroups) {
    const matches = [];
    const placeholder = () => ({ nickName: '待定', avatarUrl: '../../images/avatar_boy.png', gender: 'male' });
    const courtCount = this.data.courtCount || 1; // 使用用户设置的场地数，默认为1
    
    // 16组直接配对，共8场比赛
    for (let i = 0; i < 8; i++) {
      const team1Index = i * 2;
      const team2Index = i * 2 + 1;
      
      matches.push({
        id: `R16_${i + 1}`,
        stage: 'R16',
        stageOrder: 1,
        stageName: '16进8',
        position: i + 1,
        left: partnerGroups[team1Index],
        right: partnerGroups[team2Index],
        status: 'ready',
        courtIndex: i % courtCount, // 使用用户设置的场地数
        round: 1,
        nextMatchId: `QF${Math.floor(i / 2) + 1}`,
        nextMatchSide: i % 2 === 0 ? 'left' : 'right'
      });
    }
    
    // 生成四分之一决赛（8进4）
    const quarterFinalMatches = [
      { id: 'QF1', position: 1, nextMatchId: 'SF1', nextMatchSide: 'left' },
      { id: 'QF2', position: 2, nextMatchId: 'SF1', nextMatchSide: 'right' },
      { id: 'QF3', position: 3, nextMatchId: 'SF2', nextMatchSide: 'left' },
      { id: 'QF4', position: 4, nextMatchId: 'SF2', nextMatchSide: 'right' }
    ];
    
    quarterFinalMatches.forEach((match, qfIndex) => {
      matches.push({
        id: match.id,
        stage: 'QF',
        stageOrder: 2,
        stageName: '四分之一决赛',
        position: match.position,
        left: [placeholder(), placeholder()],
        right: [placeholder(), placeholder()],
        status: 'ready',
        courtIndex: qfIndex % courtCount, // 使用用户设置的场地数
        round: 2,
        nextMatchId: match.nextMatchId,
        nextMatchSide: match.nextMatchSide
      });
    });
    
    // 半决赛（4进2）
    matches.push({
      id: 'SF1',
      stage: 'SF',
      stageOrder: 3,
      stageName: '半决赛',
      position: 1,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'ready',
      courtIndex: 0,
      round: 3,
      nextMatchId: 'F1',
      nextMatchSide: 'left'
    });
    
    matches.push({
      id: 'SF2',
      stage: 'SF',
      stageOrder: 3,
      stageName: '半决赛',
      position: 2,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'ready',
      courtIndex: 1,
      round: 3,
      nextMatchId: 'F1',
      nextMatchSide: 'right'
    });
    
    // 第三名比赛
    matches.push({
      id: 'TP1',
      stage: 'TP',
      stageOrder: 4,
      stageName: '第三名决赛',
      position: 1,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'pending',
      courtIndex: 0,
      round: 4
    });

    // 决赛
    matches.push({
      id: 'F1',
      stage: 'F',
      stageOrder: 5,
      stageName: '决赛',
      position: 1,
      left: [placeholder(), placeholder()],
      right: [placeholder(), placeholder()],
      status: 'ready',
      courtIndex: 0,
      round: 5
    });
    
    return matches;
  },
  
  onGenerateMatch() {
    if (!this.data.isCreator) {
      wx.showToast({ title: '只有创建人才能生成对阵', icon: 'none' });
      return;
    }
    // 一键直接生成淘汰赛对阵；如已存在则二次确认覆盖
    if (this.data.showRegenMatchBtn) {
      wx.showModal({
        title: '提示',
        content: '重新生成对阵？现有对局和成绩将全部清除',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this._doGenerateMatch();
          }
        }
      });
    } else {
      this._doGenerateMatch();
    }
  },
  onConfirmMatchModal() {
    this._doGenerateMatch();
    this.setData({ showMatchModal: false });
  },
  _doGenerateMatch() {
    // 校验报名人数
    if (this.data.signupCount < 6) {
      wx.showToast({
        title: '至少需要6人才能生成对阵',
        icon: 'none'
      });
      return;
    }
    // 校验免责声明
    if (!this.data.disclaimerChecked) {
      wx.showToast({
        title: '请先勾选免责声明',
        icon: 'none'
      });
      return;
    }
    
    // 根据循环次数计算总场数
    const players = this.data.signupList.filter(item => item);
    const groupCount = players.length / 2; // 搭档组数量
    
    // 基于报名顺序构建搭档组
    const partnerGroups = [];
    for (let i = 0; i < players.length; i += 2) {
      const p1 = players[i];
      const p2 = players[i + 1];
      if (p1 && p2) {
        partnerGroups.push([p1, p2]);
      } else if (p1 && !p2) {
        // 这种情况理论上不会发生，因为前面已经校验了人数为双数
        console.warn('发现单数选手，这不应该发生');
      }
    }

    let matchList;

    // 根据组数生成合适的淘汰赛对阵
    if (partnerGroups.length === 4) {
      // 4组直接半决赛
      matchList = this.generateFourTeamElimination(partnerGroups);
    } else if (partnerGroups.length === 8) {
      // 8组分成2组，每组4队
      matchList = this.generateEightGroupElimination(partnerGroups);
    } else if (partnerGroups.length === 12 || partnerGroups.length === 16) {
      // 12组和16组分成4组
      matchList = this.generateFourGroupElimination(partnerGroups);
    } else if (partnerGroups.length === 5 || partnerGroups.length === 6 || partnerGroups.length === 7) {
      // 5-7组打循环赛决出4强
      matchList = this.generateRoundRobin(partnerGroups, 4);
    } else if (partnerGroups.length === 9 || partnerGroups.length === 10 || partnerGroups.length === 11 || 
               partnerGroups.length === 13 || partnerGroups.length === 14 || partnerGroups.length === 15) {
      // 9-11组和13-15组打循环赛决出8强
      matchList = this.generateRoundRobin(partnerGroups, 8);
    } else {
      wx.showToast({ title: '当前支持4-16组（8-32人）', icon: 'none' });
      return;
    }
    
    // 清空比分和状态
    (matchList || []).forEach(match => {
      match.score = null;
      if (!match.status) match.status = 'ready';
    });
    
    const raceId = this.raceId;
    
    // 保存到本地存储
    this.localDataManager.saveMatches(raceId, [{ raceId, matchList }]);
    
    // 更新比赛信息
    const raceData = this.localDataManager.getRace(raceId);
    if (raceData) {
      raceData.status = '计分中';
      raceData.matchList = matchList;
      this.localDataManager.saveRace(raceData);
    }
    
    wx.showToast({ title: '对阵已生成' });
    this.loadMatchList();
    this.setData({ selectedItemIndex: 1 });
  },
  onCloseMatchModal() {
    this.setData({ showMatchModal: false });
  },
  onStartMatch(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const { filteredMatchList, matchList } = this.data;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在固搭循环赛中，由于可能存在重复的搭档组组合，我们需要使用更精确的匹配方式
    // 不仅要匹配搭档组，还要匹配轮次和场地信息
    const leftNames = target.left.map(p => p.nickName).join(',');
    const rightNames = target.right.map(p => p.nickName).join(',');
    const realIndex = matchList.findIndex(item =>
      item.left.map(p => p.nickName).join(',') === leftNames &&
      item.right.map(p => p.nickName).join(',') === rightNames &&
      item.round === target.round &&
      item.courtIndex === target.courtIndex
    );
    
    if (realIndex === -1) return;
    
    matchList[realIndex].status = 'playing';
    this.setData({ matchList }, () => {
      this.filterMatchList();
    });
  },
  
  onCancelMatch(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const { filteredMatchList, matchList } = this.data;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在固搭循环赛中，由于可能存在重复的搭档组组合，我们需要使用更精确的匹配方式
    // 不仅要匹配搭档组，还要匹配轮次和场地信息
    const leftNames = target.left.map(p => p.nickName).join(',');
    const rightNames = target.right.map(p => p.nickName).join(',');
    const realIndex = matchList.findIndex(item =>
      item.left.map(p => p.nickName).join(',') === leftNames &&
      item.right.map(p => p.nickName).join(',') === rightNames &&
      item.round === target.round &&
      item.courtIndex === target.courtIndex
    );
    
    if (realIndex === -1) return;
    
    matchList[realIndex].status = 'ready';
    this.setData({ matchList }, () => {
      this.filterMatchList();
    });
  },
  onDisclaimerChange(e) {
    this.setData({ disclaimerChecked: e.detail.value.length > 0 });
  },
  onTabChange(e) {
    const idx = Number(e.currentTarget.dataset.index);
    this.setData({ selectedItemIndex: idx });
    
    // 如果切换到成绩标签页，重新计算成绩
    if (idx === 2) {
      this.calculateResults();
    }
  },
  onSelectRoundType(e) {
    const roundType = e.detail.value;
    this.setData({
      roundType: roundType
    });
  },
  onCustomRoundCountInput(e) {
    const value = e.detail.value;
    this.setData({ customRoundCount: parseInt(value) || 0 });
  },
     // 更新搭档组信息
   updatePartnerGroups() {
     const signupList = this.data.signupList || [];
     const partnerGroups = [];
     
     // 计算应该显示的组数（每两人一组）
     const groupCount = Math.ceil(signupList.length / 2);
     
     // 按顺序每两个人配对，形成搭档组
     for (let i = 0; i < groupCount; i++) {
       const player1 = signupList[i * 2];
       const player2 = signupList[i * 2 + 1];
       
       partnerGroups.push({
         index: i + 1,
         player1: player1,
         player2: player2
       });
     }
     
     // 检查是否有重复选手出现在不同搭档组中
     const playerNames = new Set();
     const duplicatePlayers = [];
     
     partnerGroups.forEach((group, groupIndex) => {
       const players = [group.player1, group.player2].filter(p => p && p.nickName);
       players.forEach(player => {
         if (playerNames.has(player.nickName)) {
           duplicatePlayers.push({
             name: player.nickName,
             groupIndex: groupIndex + 1
           });
         } else {
           playerNames.add(player.nickName);
         }
       });
     });
     
     if (duplicatePlayers.length > 0) {
       console.warn('发现重复选手在不同搭档组中:', duplicatePlayers);
       // 这里可以添加处理重复选手的逻辑，比如合并搭档组或重新分配
     }
     
     this.setData({ partnerGroups });
   },
   updateCourtCountLimit() {
     const n = this.data.signupList.filter(item => item).length;
     let maxCourt = 1;
     if (n >= 16) maxCourt = 4;
     else if (n >= 12) maxCourt = 3;
     else if (n >= 8) maxCourt = 2;
     else maxCourt = 1;
     this.setData({ maxCourtCount: Math.max(1, maxCourt) });
   },
   onCourtRadioGroupChange(e) {
     if (!this.data.isCreator) {
       wx.showToast({ title: '只有创建人才能修改', icon: 'none' });
       return;
     }
     const value = Number(e.detail.value);
     this.setData({ courtCount: value });
     // 同步到本地存储
     const raceId = this.options && this.options.id;
     const raceData = this.localDataManager.getRace(raceId);
     if (raceData) {
       raceData.courtCount = value;
       this.localDataManager.saveRace(raceData);
       wx.showToast({ title: '场地数已更新' });
     } else {
       wx.showToast({ title: '比赛不存在', icon: 'none' });
     }
   },
  loadSignupList() {
    const raceId = this.options && this.options.id;
    if (!raceId) return;
    
    const signupDataList = this.localDataManager.getSignups(raceId);
    // 根据报名的最大序号动态扩容，确保全部显示
    let maxPlayers = this.data.maxPlayers || 6;
    let highestOrder = -1;
    if (signupDataList && signupDataList.length > 0) {
      signupDataList.forEach(item => {
        if (typeof item.order === 'number' && item.order >= 0) {
          if (item.order > highestOrder) highestOrder = item.order;
        }
      });
      // 需要的最小长度为最高序号+1，且为偶数
      let needed = Math.max(maxPlayers, highestOrder + 1);
      if (needed % 2 !== 0) needed += 1;
      maxPlayers = needed;
    }
    
    // 创建固定长度的数组，保持位置信息
    let signupList = new Array(maxPlayers).fill(null);
    
    // 如果没有报名数据，确保至少显示8个空位
    if (maxPlayers < 8) {
      signupList = new Array(8).fill(null);
      maxPlayers = 8;
    }
    
    if (signupDataList && signupDataList.length > 0) {
      // 将报名数据按order放置到对应位置（不再丢弃越界项）
      signupDataList.forEach(item => {
        if (typeof item.order === 'number' && item.order >= 0) {
          if (item.order >= signupList.length) {
            // 扩容以容纳该位置
            const targetLen = item.order + 1 + ((item.order + 1) % 2); // 保持偶数
            while (signupList.length < targetLen) signupList.push(null);
            maxPlayers = signupList.length;
          }
          const signupItem = {};
          if (item.userInfo) {
            for (let key in item.userInfo) {
              if (item.userInfo.hasOwnProperty(key)) {
                signupItem[key] = item.userInfo[key];
              }
            }
          }
          signupItem._id = item._id;
          signupItem.order = item.order;
          signupList[item.order] = signupItem;
        }
      });
    }
    
    let actualCount = signupList.filter(item => item !== null).length;
    
    // 将最新容量写回比赛信息
    const raceDataUpdate = this.localDataManager.getRace(raceId);
    if (raceDataUpdate) {
      raceDataUpdate.maxPlayers = maxPlayers;
      this.localDataManager.saveRace(raceDataUpdate);
    }
    
    const raceData = this.localDataManager.getRace(raceId);
    const data2 = raceData || {};
    
    // 确保至少显示8个报名框
    if (signupList.length < 8) {
      signupList = new Array(8).fill(null);
      maxPlayers = 8;
    }
    
    this.setData({
      signupList,
      signupCount: actualCount,
      appliedCount: actualCount,
      maxPlayers,
      raceTitle: data2.title || '',
      'raceInfo.totalNum': actualCount
    }, () => {
      this.updateSignupCount();
      this.updatePartnerGroups();
    });
  },
  loadMatchList() {
    const raceId = this.options && this.options.id;
    if (!raceId) return;
    
    const matchData = this.localDataManager.getMatches(raceId);
    
    if (matchData && matchData.length) {
      // 检查数据格式：如果是对象数组且包含 matchList 属性，则取 matchList
      let matchList;
      if (matchData[0] && matchData[0].matchList) {
        matchList = matchData[0].matchList;
      } else {
        // 否则直接使用 matchData
      matchList = matchData;
    }
    
    // 计算已完成的比赛数量
    const finishedCount = matchList.filter(match => match.status === 'finished').length;
    
    this.setData({ matchList, finishedCount }, () => {
        this.updatePartnerGroups(); // 更新搭档组信息
        this.rebuildStageTabs();
        this.buildBracketColumns();
        this.filterMatchList();
        this.calculateResults(); // 加载比赛后计算成绩
        
        // 检查是否所有比赛都已完成，如果是则切换到成绩页面
        const allFinished = matchList.every(match => match.status === 'finished');
        if (allFinished && matchList.length > 0) {
          this.setData({ selectedItemIndex: 2 });
        }
        

      });
    }
  },

  filterMatchList() {
    const { matchList, scoreTabIndex, stageTabCodes } = this.data;
    
    // 确保 matchList 是数组
    if (!Array.isArray(matchList)) {
      this.setData({ 
        filteredMatchList: [], 
        scoreTabList: [] 
      });
      return;
    }
    
    // 排序：淘汰赛优先按 stageOrder(QF→SF→F)，再按 position；否则保持原顺序
    const sorted = matchList.slice().sort((a, b) => {
      const ao = a.stageOrder || 99; const bo = b.stageOrder || 99;
      if (ao !== bo) return ao - bo;
      const ap = a.position || 0; const bp = b.position || 0;
      if (ap !== bp) return ap - bp;
      return 0;
    });
    
    let filtered = sorted;
    if (Array.isArray(stageTabCodes) && typeof scoreTabIndex === 'number' && stageTabCodes[scoreTabIndex]) {
      const stageCode = stageTabCodes[scoreTabIndex];
      if (stageCode === 'ALL') {
        filtered = sorted;
      } else {
        filtered = sorted.filter(item => item.stage === stageCode);
      }
    }
    // 同步刷新计数
    this.rebuildStageTabs();
    const bracketColumns = this.buildBracketColumns();
    this.setData({ 
      filteredMatchList: filtered,
      bracketColumns: bracketColumns
    });
  },
   onQuickSignup() {
     this.setData({ showQuickSignupModal: true, quickSignupText: '' });
   },
   onCloseQuickSignup() {
     this.setData({ showQuickSignupModal: false, quickSignupText: '' });
   },
   onQuickSignupInput(e) {
     this.setData({ quickSignupText: e.detail.value });
   },
   onConfirmQuickSignup() {
     const text = this.data.quickSignupText || '';
     // 逐行匹配，兼容多种点号和行首空格、全角空格、点号后空格
     const lines = text.split('\n').map(line => line.replace(/^\s+|\s+$/g, ''));
     const filterKeywords = ['场', '封车', '锁死', '钥匙'];
     // 允许点号后有任意空格，且点号可为.、．、。 、
     const partnerGroups = lines
       .filter(line => /^[\s\u3000]*\d+[\.．。、]\s*[^\s]+/.test(line))
       .map(line => line.replace(/^[\s\u3000]*\d+[\.．。、]\s*/, ''))
       .filter(name => !filterKeywords.some(keyword => name.includes(keyword)));
     if (!partnerGroups.length) {
       wx.showToast({ title: '请粘贴有效的接龙内容', icon: 'none' });
       return;
     }
     
     // 解析搭档组合，支持空格或+分割
     const signupList = [];
     let order = 0;
     
     for (const partnerGroup of partnerGroups) {
      // 优先按+分割，其次按空格兼容
      let partners = partnerGroup.split('+');
      if (partners.length < 2) {
        partners = partnerGroup.split(/\s+/);
      }
      partners = partners.filter(partner => partner.trim());
       
       if (partners.length >= 2) {
        // 双打组合：两个搭档分配连续的order值，确保他们被分到相邻位置
        const player1Order = order;
        const player2Order = order + 1;
        
         // 添加第一个搭档
         signupList.push({
           nickName: partners[0].trim(),
           avatarUrl: '../../images/avatar_boy.png',
           gender: 'male',
          order: player1Order
         });
         
        // 添加第二个搭档（使用连续的order值）
         signupList.push({
           nickName: partners[1].trim(),
           avatarUrl: '../../images/avatar_boy.png',
           gender: 'male',
          order: player2Order
         });
        
        order += 2; // 每个双打组合使用两个连续的order值
       } else if (partners.length === 1) {
        // 单个报名的情况
         signupList.push({
           nickName: partners[0].trim(),
           avatarUrl: '../../images/avatar_boy.png',
           gender: 'male',
           order: order++
         });
       }
     }
     
     const raceId = this.options && this.options.id;
     wx.showModal({
       title: '提示',
       content: '导入报名会清空原来的报名信息，是否导入？',
       confirmText: '导入',
       cancelText: '取消',
       success: (res) => {
         if (res.confirm) {
           // 彻底清空报名，等待清空完成后再导入
           setTimeout(async () => { await this.importSignupBatch(signupList, raceId); }, 100);
         }
       }
     });
   },
   onQuickSignupBtn() {
     this.setData({ showQuickSignupModal: true });
   },
   async importSignupBatch(signupList, raceId) {

     // 清空现有报名
     this.localDataManager.clearSignups(raceId);
     
     // 批量添加到本地存储
     for (const item of signupList) {
       const signupData = {
         raceId,
         order: item.order,
         userInfo: {
           nickName: item.nickName,
           avatarUrl: item.avatarUrl,
           gender: item.gender
         }
       };
       this.localDataManager.addSignup(raceId, signupData);
     }
     
     wx.showToast({ title: '已导入报名', icon: 'success' });
     this.setData({ showQuickSignupModal: false, quickSignupText: '' });
     
     const signupDataList = this.localDataManager.getSignups(raceId);

     this.loadSignupList();
   },
   onEditSignup(e) {
     const index = e.currentTarget.dataset.index;
     const { signupList } = this.data;
     const item = signupList[index];
     if (!item || !item.nickName) return;
     wx.showModal({
       title: '编辑报名昵称',
       editable: true,
       placeholderText: '请输入新昵称',
       content: item.nickName,
       success: (res) => {
         if (res.confirm && res.content && res.content !== item.nickName) {
           // 更新本地存储
           const raceId = this.options && this.options.id;
           const signupDataList = this.localDataManager.getSignups(raceId);
           const targetSignup = signupDataList.find(signup => 
             signup.userInfo.nickName === item.nickName && signup.order === item.order
           );
           
           if (targetSignup) {
             targetSignup.userInfo.nickName = res.content;
             this.localDataManager.updateSignup(raceId, targetSignup);
             wx.showToast({ title: '已修改' });
             this.loadSignupList();
           } else {
             wx.showToast({ title: '修改失败', icon: 'none' });
           }
         }
       }
     });
   },
  // 编辑报名弹窗输入
  onEditSignupNameInput(e) {
    // 实时更新 editSignupName，确保输入框和数据同步
    this.setData({ editSignupName: e.detail.value });
  },
  onEditSignupGenderSelect(e) {
    this.setData({ editSignupGender: e.currentTarget.dataset.gender });
  },
  onConfirmEditSignup() {
    const { editSignupIndex, editSignupName, editSignupGender, signupList } = this.data;
    const item = signupList[editSignupIndex];
    if (!item || !editSignupName.trim() || !item._id) {
      wx.showToast({ title: '数据异常', icon: 'none' });
      return;
    }
    // 根据性别切换默认头像
    let avatarUrl = item.avatarUrl;
    if (editSignupGender === 'female') {
      avatarUrl = '../../images/avatar_girl.png';
    } else if (editSignupGender === 'male') {
      avatarUrl = '../../images/avatar_boy.png';
    }
    // 更新本地存储中的报名信息
    const raceId = this.options && this.options.id;
    const signupDataList = this.localDataManager.getSignups(raceId);
    const targetSignup = signupDataList.find(signup => signup._id === item._id);
    
    if (targetSignup) {
      targetSignup.userInfo.nickName = editSignupName;
      targetSignup.userInfo.gender = editSignupGender;
      targetSignup.userInfo.avatarUrl = avatarUrl;
      this.localDataManager.updateSignup(raceId, targetSignup);
      
      wx.showToast({ title: '已修改' });
      this.setData({ showEditSignupModal: false }, () => {
        this.loadSignupList();
      });
    } else {
      wx.showToast({ title: '修改失败', icon: 'none' });
      console.error('报名信息修改失败：未找到对应记录');
    }
  },
  onCancelEditSignup() {
    this.setData({ showEditSignupModal: false });
  },
  onBack() {
    // 返回到比赛列表页
    wx.navigateBack({
      fail: () => {
        // 如果返回失败，则跳转到列表页
        wx.switchTab({ url: '/pages/list/list' });
      }
    });
  },
  
  // 计分相关方法
  onOpenScoreModal(e) {
    const filteredIndex = e.currentTarget.dataset.index;
    const { filteredMatchList, matchList } = this.data;
    const target = filteredMatchList[filteredIndex];
    
    if (!target) return;
    
    // 在固搭循环赛中，由于可能存在重复的搭档组组合，我们需要使用更精确的匹配方式
    // 不仅要匹配搭档组，还要匹配轮次和场地信息
    const leftNames = target.left.map(p => p.nickName).join(',');
    const rightNames = target.right.map(p => p.nickName).join(',');
    const realIndex = matchList.findIndex(item =>
      item.left.map(p => p.nickName).join(',') === leftNames &&
      item.right.map(p => p.nickName).join(',') === rightNames &&
      item.round === target.round &&
      item.courtIndex === target.courtIndex
    );
    
    if (realIndex === -1) return;
    
    const match = matchList[realIndex];
    
    this.setData({
      scoreModalVisible: true,
      scoreModalIndex: realIndex,
      scoreLeft: match.score ? match.score.left : '',
      scoreRight: match.score ? match.score.right : '',
      scoreModalLeft: match.left || [],
      scoreModalRight: match.right || []
    });
  },
  
  onScoreInput(e) {
    const { side } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    // 只允许输入数字
    if (value && !/^\d*$/.test(value)) {
      wx.showToast({ title: '只能输入数字', icon: 'none' });
      return;
    }
    
    this.setData({ [side]: value });
  },
  
  onConfirmScoreModal() {
    const { scoreModalIndex, scoreLeft, scoreRight, matchList } = this.data;
    
    if (!scoreLeft || !scoreRight) {
      wx.showToast({ title: '请输入完整比分', icon: 'none' });
      return;
    }
    
    if (isNaN(Number(scoreLeft)) || isNaN(Number(scoreRight))) {
      wx.showToast({ title: '比分只能输入数字', icon: 'none' });
      return;
    }
    
    if (scoreModalIndex === -1 || !matchList[scoreModalIndex]) {
      wx.showToast({ title: '比赛数据异常', icon: 'none' });
      return;
    }
    
    // 保存比分与完成状态
    const currentMatch = matchList[scoreModalIndex];
    currentMatch.score = { left: Number(scoreLeft), right: Number(scoreRight) };
    currentMatch.status = 'finished';
        this.setData({ matchList }, () => {
           this.rebuildStageTabs();
           this.buildBracketColumns();

         });

    // 如果是淘汰赛，推进胜者到下一场
    if (currentMatch.nextMatchId) {
      const leftSum = Number(scoreLeft);
      const rightSum = Number(scoreRight);
      const winnerSide = leftSum > rightSum ? 'left' : 'right';
      const winnerTeam = currentMatch[winnerSide];

      const nextIndex = matchList.findIndex(m => m.id === currentMatch.nextMatchId);
      if (nextIndex !== -1) {
        const nextMatch = matchList[nextIndex];
        const placeSide = currentMatch.nextMatchSide || 'left';
        nextMatch[placeSide] = winnerTeam;
        // 如果另一侧也已就绪，确保状态可比赛
        if (Array.isArray(nextMatch.left) && Array.isArray(nextMatch.right)) {
          if (!nextMatch.score && nextMatch.status !== 'finished') {
            nextMatch.status = 'ready';
          }
        }
      }
    }
    
    // 如果是循环赛比赛，检查是否需要更新半决赛参赛者
    if (currentMatch.stage === 'RR') {
      // 检查所有循环赛是否都已完成
      const roundRobinMatches = matchList.filter(m => m.stage === 'RR');
      const allRoundRobinFinished = roundRobinMatches.every(m => m.status === 'finished');
      
      if (allRoundRobinFinished) {
        // 循环赛全部完成，更新半决赛参赛者
        this.updateKnockoutFromGroupStage();
      }
    }

    // 计算胜者和败者
    const leftSum = Number(scoreLeft);
    const rightSum = Number(scoreRight);
    const winnerSide = leftSum > rightSum ? 'left' : 'right';
    const loserSide = leftSum > rightSum ? 'right' : 'left';
    
    // 如果是总决赛比赛，设置冠军信息
    if (currentMatch.stage === 'F') {
      currentMatch.winner = currentMatch[winnerSide];
      currentMatch.loser = currentMatch[loserSide];
    }
    
    // 如果是半决赛比赛，收集败者信息用于第三名
    if (currentMatch.stage === 'SF') {
      currentMatch.loser = currentMatch[loserSide];
      
      // 检查是否所有半决赛都已完成，如果是则更新第三名比赛
      const semiFinalMatches = matchList.filter(m => m.stage === 'SF');
      const allSemiFinished = semiFinalMatches.every(m => m.status === 'finished');
      
      if (allSemiFinished && semiFinalMatches.length === 2) {
        // 获取两个半决赛的败者
        const losers = semiFinalMatches.map(m => m.loser).filter(Boolean);
        if (losers.length === 2) {
          // 查找第三名比赛并更新参赛者
          const thirdPlaceMatch = matchList.find(m => m.stage === 'TP');
          if (thirdPlaceMatch) {
            thirdPlaceMatch.left = losers[0];
            thirdPlaceMatch.right = losers[1];
            thirdPlaceMatch.status = 'ready';

          }
        }
      }
    }
    
    // 设置败者（如果还没有设置的话）
    if (!currentMatch.loser) {
      currentMatch.loser = currentMatch[loserSide];
    }

    // 判断是否所有比赛完成
    const allFinished = matchList.every(match => match.status === 'finished');
    if (allFinished) {
      const raceData = this.localDataManager.getRace(this.raceId);
      if (raceData) {
        raceData.status = '已完赛';
        this.localDataManager.saveRace(raceData);
      }
      this.setData({ selectedItemIndex: 2 }, () => {
        wx.pageScrollTo({ scrollTop: 0, duration: 300 });
      });
      wx.showToast({ title: '所有比赛已完成，已切换到成绩页面', icon: 'success' });
    } else {
      wx.showToast({ title: '比分已保存', icon: 'success' });
    }
    
    // 计算已完成的比赛数量
    const finishedCount = matchList.filter(match => match.status === 'finished').length;
    
    this.setData({
      matchList,
      scoreModalVisible: false,
      scoreModalIndex: -1,
      scoreLeft: '',
      scoreRight: '',
      finishedCount: finishedCount
    }, () => {
      this.rebuildStageTabs();
      // 如果当前阶段全部结束，自动切到下一阶段
      const { stageTabCodes, scoreTabIndex } = this.data;
      const stageCode = currentMatch.stage;
      const stageAllFinished = matchList.filter(m => m.stage === stageCode).every(m => m.status === 'finished');
      let nextIndex = scoreTabIndex;
      if (stageAllFinished && Array.isArray(stageTabCodes)) {
        const firstIdx = stageTabCodes.findIndex(c => c === stageCode);
        if (firstIdx !== -1 && firstIdx + 1 < stageTabCodes.length) {
          nextIndex = firstIdx + 1;
        }
      }
      this.setData({ scoreTabIndex: nextIndex }, () => {
      this.filterMatchList();
      });
      this.calculateResults();
    });
    
    const raceId = this.raceId;
    this.localDataManager.saveMatches(raceId, [{ raceId, matchList }]);
  },
  
  // 关闭比分弹窗
  onCloseScoreModal() {
    this.setData({
      scoreModalVisible: false,
      scoreModalIndex: -1,
      scoreLeft: '',
      scoreRight: ''
    });
  },
  
  // 计算成绩排名
  calculateResults() {
    const { matchList } = this.data;
    
    // 只有在所有比赛都完成后才计算和显示最终成绩
    const allFinished = matchList.every(match => match.status === 'finished' && match.score);
    
    if (!allFinished) {
      // 比赛未全部完成，不显示成绩
      this.setData({ resultList: [] });
      return;
    }
    
    const finishedMatches = matchList.filter(match => match.status === 'finished' && match.score);
    
    if (finishedMatches.length === 0) {
      this.setData({ resultList: [] });
      return;
    }
    
    // 首先检查淘汰赛结果，确定冠亚季军
    const finalMatch = matchList.find(m => m.stage === 'F');
    const thirdPlaceMatch = matchList.find(m => m.stage === 'TP');
    
    // 获取冠亚季军队伍
    let champion, runnerUp, thirdPlace;
    
    if (finalMatch && finalMatch.score) {
      // 确定冠军和亚军
      if (finalMatch.score.left > finalMatch.score.right) {
        champion = finalMatch.left;
        runnerUp = finalMatch.right;
      } else {
        champion = finalMatch.right;
        runnerUp = finalMatch.left;
      }
    }
    
    if (thirdPlaceMatch && thirdPlaceMatch.score) {
      // 确定季军
      if (thirdPlaceMatch.score.left > thirdPlaceMatch.score.right) {
        thirdPlace = thirdPlaceMatch.left;
      } else {
        thirdPlace = thirdPlaceMatch.right;
      }
    }
    
    // 统计所有搭档组成绩（用于显示完整排名）
    const comboMap = {};
    
    finishedMatches.forEach(match => {
      const leftKey = match.left.map(p => p.nickName).join('+');
      const rightKey = match.right.map(p => p.nickName).join('+');
      
      if (!comboMap[leftKey]) {
        comboMap[leftKey] = { 
          combo: match.left.slice(), 
          win: 0, 
          lose: 0,
          score: 0,
          players: match.left.map(p => p.nickName).join('+'),
          rank: 0 // 初始排名为0
        };
      }
      if (!comboMap[rightKey]) {
        comboMap[rightKey] = { 
          combo: match.right.slice(), 
          win: 0, 
          lose: 0,
          score: 0,
          players: match.right.map(p => p.nickName).join('+'),
          rank: 0 // 初始排名为0
        };
      }
      
      if (match.score.left > match.score.right) {
        comboMap[leftKey].win += 1;
        comboMap[leftKey].score += match.score.left - match.score.right;
        comboMap[rightKey].lose += 1;
        comboMap[rightKey].score -= match.score.left - match.score.right;
      } else {
        comboMap[rightKey].win += 1;
        comboMap[rightKey].score += match.score.right - match.score.left;
        comboMap[leftKey].lose += 1;
        comboMap[leftKey].score -= match.score.right - match.score.left;
      }
    });
    
    // 生成成绩数组
    const resultList = Object.values(comboMap).map((item, idx) => {
      const resultItem = {};
      // 复制item的所有属性
      for (let key in item) {
        if (item.hasOwnProperty(key)) {
          resultItem[key] = item[key];
        }
      }
      resultItem.idx = idx;
      return resultItem;
    });
    
    // 设置冠亚季军的排名
    if (champion) {
      const championKey = champion.map(p => p.nickName).join('+');
      if (comboMap[championKey]) {
        comboMap[championKey].rank = 1;
      }
    }
    
    if (runnerUp) {
      const runnerUpKey = runnerUp.map(p => p.nickName).join('+');
      if (comboMap[runnerUpKey]) {
        comboMap[runnerUpKey].rank = 2;
      }
    }
    
    if (thirdPlace) {
      const thirdPlaceKey = thirdPlace.map(p => p.nickName).join('+');
      if (comboMap[thirdPlaceKey]) {
        comboMap[thirdPlaceKey].rank = 3;
      }
    }
    
    // 重新生成结果数组，并按排名排序
    const finalResultList = Object.values(comboMap).map((item, idx) => {
      const resultItem = {};
      // 复制item的所有属性
      for (let key in item) {
        if (item.hasOwnProperty(key)) {
          resultItem[key] = item[key];
        }
      }
      resultItem.idx = idx;
      return resultItem;
    });
    
    // 先按排名排序，没有排名的按胜场和净胜分排序
    finalResultList.sort((a, b) => {
      // 有排名的排在前面
      if (a.rank > 0 && b.rank > 0) return a.rank - b.rank;
      if (a.rank > 0) return -1;
      if (b.rank > 0) return 1;
      // 没有排名的按胜场和净胜分排序
      return b.win - a.win || b.score - a.score;
    });
    
    // 只显示前三名
    const topThreeResultList = finalResultList.slice(0, 3);
    
    this.setData({ resultList: topThreeResultList });
    
    // 计算循环赛排名
    this.calculateRoundRobinResults();
    
    // 检查是否需要处理小组赛晋级
    this.updateKnockoutFromGroupStage();
    
    setTimeout(() => {
      this.updateKnockoutFromGroupStage();
    }, 1000);
  },
  
  // 小组赛晋级到淘汰赛
  updateKnockoutFromGroupStage() {
    const { matchList } = this.data;
    const groupStageMatches = matchList.filter(m => m.stage === 'GS');
    const roundRobinMatches = matchList.filter(m => m.stage === 'RR');
    const knockoutMatches = matchList.filter(m => m.stage === 'SF' || m.stage === 'QF');
    
    // 如果没有小组赛/循环赛或淘汰赛，不处理晋级
    if ((groupStageMatches.length === 0 && roundRobinMatches.length === 0) || knockoutMatches.length === 0) {
      return;
    }
    
    // 检查小组赛是否全部完成（如果有小组赛）
    const allGroupFinished = groupStageMatches.length > 0 ? groupStageMatches.every(m => m.status === 'finished') : true;

    // 检查循环赛是否全部完成（如果有循环赛）
    const allRoundRobinFinished = roundRobinMatches.length > 0 ? roundRobinMatches.every(m => m.status === 'finished') : true;

    
    // 如果有小组赛且未全部完成，或者有循环赛且未全部完成，不处理晋级
    if ((groupStageMatches.length > 0 && !allGroupFinished) || (roundRobinMatches.length > 0 && !allRoundRobinFinished)) {

      return;
    }
    
    // 计算小组赛成绩
    const groupResults = this.calculateGroupResults();

    // 更新淘汰赛对阵
    let updated = false;
    const updatedMatchList = matchList.map(match => {
      if (match.stage === 'SF') {
        // 判断是6组还是7组的情况
        const totalGroups = this.data.partnerGroups ? this.data.partnerGroups.length : 6;
        
        if (totalGroups === 6) {
          // 检查是否有循环赛（完全循环赛）
          const hasRoundRobin = roundRobinMatches.length > 0;
          
          if (hasRoundRobin) {
            // 完全循环赛情况：循环赛第1名 vs 循环赛第4名，循环赛第2名 vs 循环赛第3名
            if (match.id === 'SF1') {
              // SF1: 循环赛第1名 vs 循环赛第4名
              if (groupResults.length >= 4) {
                const firstPlace = groupResults[0]; // 循环赛第1名
                const fourthPlace = groupResults[3]; // 循环赛第4名
                
                if (firstPlace && fourthPlace && (!match.left[0].nickName || match.left[0].nickName === '待定')) {
                  updated = true;
                  return {
                    ...match,
                    left: firstPlace.combo,
                    right: fourthPlace.combo
                  };
                }
              }
            } else if (match.id === 'SF2') {
              // SF2: 循环赛第2名 vs 循环赛第3名
              if (groupResults.length >= 4) {
                const secondPlace = groupResults[1]; // 循环赛第2名
                const thirdPlace = groupResults[2]; // 循环赛第3名
                
                if (secondPlace && thirdPlace && (!match.left[0].nickName || match.left[0].nickName === '待定')) {
                  updated = true;
                  return {
                    ...match,
                    left: secondPlace.combo,
                    right: thirdPlace.combo
                  };
                }
              }
            }
          } else {
            // 分组循环赛情况：A组第一 vs B组第一，A组第二 vs B组第二
            if (match.id === 'SF1') {
              // SF1: A组第一 vs B组第一
              const groupFirstA = groupResults[0]; // A组第一
              const groupFirstB = groupResults[2]; // B组第一
              
              if (groupFirstA && groupFirstB && (!match.left[0].nickName || match.left[0].nickName === '待定')) {
                updated = true;
                return {
                  ...match,
                  left: groupFirstA.combo,
                  right: groupFirstB.combo
                };
              }
            } else if (match.id === 'SF2') {
              // SF2: A组第二 vs B组第二
              if (groupResults.length >= 4) {
                const groupSecondA = groupResults[1]; // A组第二
                const groupSecondB = groupResults[3]; // B组第二
                
                if (groupSecondA && groupSecondB && (!match.left[0].nickName || match.left[0].nickName === '待定')) {
                  updated = true;
                  return {
                    ...match,
                    left: groupSecondA.combo,
                    right: groupSecondB.combo
                  };
                }
              }
            }
          }
        } else if (totalGroups === 7) {
          // 7组情况：轮空组 vs 小组第一，小组第二 vs 小组第三
          if (match.id === 'SF1') {
            // SF1: 轮空组 vs 小组第一（A组第一）
            const groupFirstA = groupResults[0]; // A组第一
            if (groupFirstA && (!match.left[0].nickName || match.left[0].nickName === '待定')) {
              // 轮空组已经在生成对阵时设置好了，只需要设置右侧
              updated = true;
              return {
                ...match,
                right: groupFirstA.combo
              };
            }
          } else if (match.id === 'SF2') {
            // SF2: 小组第二 vs 小组第三
            if (groupResults.length >= 3) {
              const groupSecondA = groupResults[1]; // A组第二
              const groupThirdA = groupResults[2]; // A组第三
              if (groupSecondA && groupThirdA && (!match.left[0].nickName || match.left[0].nickName === '待定')) {
                updated = true;
                return {
                  ...match,
                  left: groupSecondA.combo,
                  right: groupThirdA.combo
                };
              }
            }
          }
        } else if (totalGroups === 8) {
          // 8组情况：直接配对淘汰赛制，第一组vs第二组，第三组vs第四组，以此类推
          if (match.stage === 'QF') {
            // 四分之一决赛：直接配对
            const pairIndex = match.position - 1; // 0-3
            const firstGroupIndex = pairIndex * 2; // 0, 2, 4, 6
            const secondGroupIndex = pairIndex * 2 + 1; // 1, 3, 5, 7
            
            if (groupResults.length >= secondGroupIndex + 1) {
              const firstGroup = groupResults[firstGroupIndex];
              const secondGroup = groupResults[secondGroupIndex];
              
              if (firstGroup && secondGroup && 
                  (!match.left[0].nickName || match.left[0].nickName === '待定' || 
                   !match.right[0].nickName || match.right[0].nickName === '待定')) {
                updated = true;
                return {
                  ...match,
                  left: firstGroup.combo,
                  right: secondGroup.combo
                };
              }
            }
          }
        } else if (totalGroups >= 9 && totalGroups <= 12) {
          // 9-12组情况：4个小组，每组前2名晋级8强
          if (match.stage === 'QF') {
            // 四分之一决赛：小组第一 vs 小组第二
            const groupIndex = Math.floor((match.position - 1) / 2);
            const isFirstMatch = (match.position - 1) % 2 === 0;
            
            if (groupResults.length >= groupIndex * 2 + (isFirstMatch ? 1 : 2)) {
              const teamRank = isFirstMatch ? 0 : 1; // 第一名或第二名
              const groupTeam = groupResults[groupIndex * 2 + teamRank];
              
              if (groupTeam && (!match.left[0].nickName || match.left[0].nickName === '待定' || !match.right[0].nickName || match.right[0].nickName === '待定')) {
                updated = true;
                if (isFirstMatch) {
                  // 第一名放在左侧
                  return {
                    ...match,
                    left: groupTeam.combo
                  };
                } else {
                  // 第二名放在右侧
                  return {
                    ...match,
                    right: groupTeam.combo
                  };
                }
              }
            }
          } else if (match.stage === 'SF') {
            // 半决赛：四分之一决赛胜者对决
            // 对于12人双败淘汰赛，半决赛直接由循环赛排名前4的队伍组成
            if (groupResults.length >= 4) {
              if (match.id === 'SF1') {
                // SF1: 循环赛第1名 vs 循环赛第4名
                updated = true;
                return {
                  ...match,
                  left: groupResults[0].combo,
                  right: groupResults[3].combo
                };
              } else if (match.id === 'SF2') {
                // SF2: 循环赛第2名 vs 循环赛第3名



                updated = true;
                return {
                  ...match,
                  left: groupResults[1].combo,
                  right: groupResults[2].combo
                };
              }
            }
          }
        } else if (totalGroups === 16) {
          // 16组情况：直接配对淘汰赛制，第一组vs第二组，第三组vs第四组，以此类推
          if (match.stage === 'QF') {
            // 四分之一决赛：直接配对
            const pairIndex = match.position - 1; // 0-3
            const firstGroupIndex = pairIndex * 2; // 0, 2, 4, 6
            const secondGroupIndex = pairIndex * 2 + 1; // 1, 3, 5, 7
            
            if (groupResults.length >= secondGroupIndex + 1) {
              const firstGroup = groupResults[firstGroupIndex];
              const secondGroup = groupResults[secondGroupIndex];
              
              if (firstGroup && secondGroup && 
                  (!match.left[0].nickName || match.left[0].nickName === '待定' || 
                   !match.right[0].nickName || match.right[0].nickName === '待定')) {
                updated = true;
                return {
                  ...match,
                  left: firstGroup.combo,
                  right: secondGroup.combo
                };
              }
            }
          }
        }
      }
      return match;
    });
    
    // 强制更新，确保循环赛完成后半决赛对阵被更新
    if (roundRobinMatches.length > 0 && allRoundRobinFinished && groupResults.length >= 4) {

      updated = true;
    }
    

    if (updated) {
      this.setData({ matchList: updatedMatchList }, () => {
        this.filterMatchList();
        // 保存到本地存储
        const raceId = this.raceId;
        this.localDataManager.saveMatches(raceId, [{ raceId, matchList: updatedMatchList }]);
      });
    }
  },
  
  // 计算循环赛成绩
  calculateGroupResults() {
    const { matchList } = this.data;
    const groupMatches = matchList.filter(m => m.stage === 'GS' || m.stage === 'RR');

    
    // 获取所有比赛组（包括循环赛）
    const allGroups = ['A组', 'B组', 'C组', 'D组', '循环赛'];
    const groups = [];
    
    allGroups.forEach(groupName => {
      let groupMatches;
      
      if (groupName === '循环赛') {
        // 循环赛处理
        groupMatches = matchList.filter(m => m.stage === 'RR');
      } else {
        // 兼容旧的小组赛数据
        groupMatches = matchList.filter(m => m.stage === 'GS' && m.stageName.includes(groupName));
      }
      
      if (groupMatches.length > 0) {
        groups.push({
          name: groupName,
          matches: groupMatches,
          isRoundRobin: groupName === '循环赛'
        });

      }
    });
    
    // 计算每个小组的成绩
    const calculateGroupRanking = (matches) => {
      const teamStats = {};
      
      matches.forEach(match => {
        const leftKey = match.left.map(p => p.nickName).join('+');
        const rightKey = match.right.map(p => p.nickName).join('+');
        
        if (!teamStats[leftKey]) {
          teamStats[leftKey] = { 
            combo: match.left, 
            win: 0, 
            lose: 0,
            score: 0,
            players: leftKey
          };
        }
        if (!teamStats[rightKey]) {
          teamStats[rightKey] = { 
            combo: match.right, 
            win: 0, 
            lose: 0,
            score: 0,
            players: rightKey
          };
        }
        
        if (match.score && match.score.left !== undefined && match.score.right !== undefined) {
          if (match.score.left > match.score.right) {
            teamStats[leftKey].win += 1;
            teamStats[leftKey].score += match.score.left - match.score.right;
            teamStats[rightKey].lose += 1;
            teamStats[rightKey].score -= match.score.left - match.score.right;
          } else {
            teamStats[rightKey].win += 1;
            teamStats[rightKey].score += match.score.right - match.score.left;
            teamStats[leftKey].lose += 1;
            teamStats[leftKey].score -= match.score.right - match.score.left;
          }
        }
      });
      
      // 排序：先按胜局，再按净胜分降序
      return Object.values(teamStats).sort((a, b) => b.win - a.win || b.score - a.score);
    };
    
    // 计算每个小组的排名
    const groupRankings = [];
    groups.forEach(group => {
      const ranking = calculateGroupRanking(group.matches);
      groupRankings.push({
        groupName: group.name,
        isRoundRobin: group.isRoundRobin,
        ranking: ranking
      });
    });
    
    // 根据比赛组数量返回排名
    const results = [];
    groupRankings.forEach(groupRanking => {
      const { isRoundRobin, ranking } = groupRanking;
      
      if (isRoundRobin) {
        // 循环赛：根据晋级数量决定取前几名
        const totalGroups = this.data.partnerGroups ? this.data.partnerGroups.length : 0;
        let advancingCount;
        
        if (totalGroups >= 5 && totalGroups <= 7) {
          // 5-7组循环赛决出4强
          advancingCount = 4;
        } else if ((totalGroups >= 9 && totalGroups <= 11) || (totalGroups >= 13 && totalGroups <= 15)) {
          // 9-11/13-15组循环赛决出8强
          advancingCount = 8;
        } else {
          // 默认取前4名
          advancingCount = 4;
        }
        
        // 取前advancingCount名
        for (let i = 0; i < advancingCount && i < ranking.length; i++) {
          results.push(ranking[i]);
        }
      } else {
        // 兼容旧的小组赛数据：每个小组取前两名
        if (ranking[0]) results.push(ranking[0]); // 第一名
        if (ranking[1]) results.push(ranking[1]); // 第二名
      }
    });
    
    return results;
  },
  
  rebuildStageTabs() {
    const matchList = Array.isArray(this.data.matchList) ? this.data.matchList : [];
    const hasR16 = matchList.some(m => m.stage === 'R16');
    const hasGroupStage = matchList.some(m => m.stage === 'GS');
    const hasRoundRobin = matchList.some(m => m.stage === 'RR');
    const hasTP = matchList.some(m => m.stage === 'TP');
    const hasQF = matchList.some(m => m.stage === 'QF');
    
    // 获取搭档组数量，用于判断是否显示8强选项
    const partnerGroupsCount = this.data.partnerGroups ? this.data.partnerGroups.length : 0;
    // 只有当搭档组数量大于等于8时才显示8强选项
    const showQuarterFinal = hasQF && partnerGroupsCount >= 8;
    
    let titles, codes;
    if (hasRoundRobin) {
      // 有循环赛的情况
      if (hasR16) {
        titles = ['总览', '循环赛', '16进8', '8强', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'RR', 'R16', 'QF', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      } else if (showQuarterFinal) {
        // 有8强比赛且搭档组数量大于等于8的情况
        titles = ['总览', '循环赛', '8强', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'RR', 'QF', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      } else {
        // 没有8强比赛或搭档组数量小于8的情况
        titles = ['总览', '循环赛', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'RR', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      }
    } else if (hasGroupStage) {
      // 兼容旧的小组赛数据情况
      if (hasR16) {
        titles = ['总览', '小组赛', '16进8', '8强', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'GS', 'R16', 'QF', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      } else if (showQuarterFinal) {
        // 有8强比赛且搭档组数量大于等于8的情况
        titles = ['总览', '小组赛', '8强', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'GS', 'QF', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      } else {
        // 没有8强比赛或搭档组数量小于8的情况
        titles = ['总览', '小组赛', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'GS', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      }
    } else {
      // 没有循环赛的情况
      if (hasR16) {
        titles = ['总览', '16进8', '8强', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'R16', 'QF', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      } else if (showQuarterFinal) {
        // 有8强比赛且搭档组数量大于等于8的情况
        titles = ['总览', '8强', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'QF', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      } else {
        // 没有8强比赛或搭档组数量小于8的情况
        titles = ['总览', '半决赛', ...(hasTP ? ['第三名'] : []), '总决赛'];
        codes = ['ALL', 'SF', ...(hasTP ? ['TP'] : []), 'F'];
      }
    }
    
    const counts = codes.map(code =>
      code === 'ALL' ? matchList.length : matchList.filter(m => m.stage === code).length
    );
    const scoreTabList = titles.map((title, i) => ({ title, count: counts[i] }));
    this.setData({ scoreTabList, stageTabCodes: codes });
  },

  // buildBracketColumns方法
  buildBracketColumns() {
    const matchList = Array.isArray(this.data.matchList) ? this.data.matchList : [];
    const columns = [];
    
    // 动态确定阶段，根据实际比赛数据
    const allStages = ['RR', 'R16', 'QF', 'SF', 'TP', 'F'];
    const existingStages = [];
    
    allStages.forEach(stage => {
      const stageMatches = matchList.filter(m => m.stage === stage);
      // 总览视图不显示循环赛和第三名决赛
      if (stageMatches.length > 0 && stage !== 'TP' && stage !== 'RR') { // 排除第三名决赛(TP)和循环赛(RR)阶段
        existingStages.push(stage);
        columns.push({
          stage,
          title: this.getStageTitle(stage),
          matches: stageMatches.sort((a, b) => a.stageOrder - b.stageOrder)
        });
      }
    });
    
    // 添加冠军信息
    const champion = matchList.find(m => m.stage === 'F' && m.status === 'finished');

    if (champion && champion.winner) {
      columns.push({
        stage: 'CHAMPION',
        title: '🏆 冠军',
        champion: champion.winner
      });
    }
    

    
    // 如果没有总决赛阶段，手动构建
    if (!columns.find(col => col.stage === 'F')) {
      // 找到半决赛列
      const semiFinalColumn = columns.find(col => col.stage === 'SF');
      
      if (semiFinalColumn && semiFinalColumn.matches.length > 0) {
        // 构建总决赛列
        const finalColumn = {
          stage: 'F',
          title: this.getStageTitle('F'),
          matches: []
        };
        
        // 从半决赛中找出获胜者，构建总决赛
        semiFinalColumn.matches.forEach(match => {
          if (match.score && match.score.left !== undefined && match.score.right !== undefined) {
            // 有比分的比赛，找出获胜者
            const winner = match.score.left > match.score.right ? match.left : match.right;
            if (winner) {
              finalColumn.matches.push({
                left: winner,
                right: null, // 待定
                score: null
              });
            }
          } else {
            // 没有比分的比赛，显示待定
            finalColumn.matches.push({
              left: null, // 待定
              right: null, // 待定
              score: null
            });
          }
        });
        

        columns.push(finalColumn);
      }
    }
    

    return columns;
  },

  getStageTitle(stage) {
    const titles = {
      'RR': '循环赛',
      'R16': '16进8',
      'QF': '8强',
      'SF': '半决赛',
      'TP': '第三名决赛',
      'F': '总决赛'
    };
    return titles[stage] || stage;
  },

  filterMatchList() {
    const { matchList, scoreTabIndex, stageTabCodes } = this.data;
    
    if (!stageTabCodes || scoreTabIndex >= stageTabCodes.length) {
      this.setData({ filteredMatchList: matchList });
      return;
    }
    
    const currentStage = stageTabCodes[scoreTabIndex];
    let filtered;
    
    if (currentStage === 'ALL') {
      filtered = matchList;
    } else {
      filtered = matchList.filter(match => match.stage === currentStage);
    }
    
    // 为每个比赛添加按钮禁用状态判断
    const enhancedFiltered = filtered.map(match => {
      const enhancedMatch = { ...match };
      
      // 检查小组赛是否全部完成
      const groupStage = matchList.filter(m => m.stage === 'GS');
      const groupStageAllFinished = groupStage.length > 0 && groupStage.every(m => m.status === 'finished');
      
      // 检查循环赛是否全部完成（用于控制半决赛和第三名比赛按钮）
      const roundRobin = matchList.filter(m => m.stage === 'RR');
      const roundRobinAllFinished = roundRobin.length > 0 && roundRobin.every(m => m.status === 'finished');
      
      // 检查8强是否全部完成（用于控制半决赛按钮）
      const quarterFinals = matchList.filter(m => m.stage === 'QF');
      const quarterFinalsAllFinished = quarterFinals.length > 0 && quarterFinals.every(m => m.status === 'finished');
      
      // 检查半决赛是否全部完成（用于控制总决赛和第三名比赛按钮）
      const semiFinals = matchList.filter(m => m.stage === 'SF');
      const semiFinalsAllFinished = semiFinals.length > 0 && semiFinals.every(m => m.status === 'finished');
      
      // 根据比赛阶段设置按钮禁用状态
      if (match.stage === 'SF') {
        // 半决赛：如果有循环赛，需要循环赛全部完成；如果有8强赛，需要8强赛全部完成
        const hasRoundRobin = roundRobin.length > 0;
        const hasQuarterFinals = quarterFinals.length > 0;
        
        if (hasRoundRobin) {
          // 有循环赛的情况：循环赛必须全部完成
          enhancedMatch.disabledStart = !roundRobinAllFinished;
          enhancedMatch.disabledScore = !roundRobinAllFinished;
        } else if (hasQuarterFinals) {
          // 有8强赛的情况：8强赛必须全部完成
          enhancedMatch.disabledStart = !quarterFinalsAllFinished;
          enhancedMatch.disabledScore = !quarterFinalsAllFinished;
        } else {
          // 既没有循环赛也没有8强赛：不禁用按钮
          enhancedMatch.disabledStart = false;
          enhancedMatch.disabledScore = false;
        }
      } else if (match.stage === 'F') {
        // 总决赛：如果半决赛未全部完成，则禁用开始比赛和记录比分按钮
        enhancedMatch.disabledStart = !semiFinalsAllFinished;
        enhancedMatch.disabledScore = !semiFinalsAllFinished;
      } else if (match.stage === 'TP') {
        // 第三名比赛：如果半决赛未全部完成，则禁用开始比赛和记录比分按钮
        enhancedMatch.disabledStart = !semiFinalsAllFinished;
        enhancedMatch.disabledScore = !semiFinalsAllFinished;
      } else {
        // 其他阶段（循环赛、小组赛、8强、16进8等）：不禁用按钮
        enhancedMatch.disabledStart = false;
        enhancedMatch.disabledScore = false;
      }
      
      return enhancedMatch;
    });
    
    this.setData({ filteredMatchList: enhancedFiltered });
  },

  // 处理计分tab切换
  onScoreTabChange(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ scoreTabIndex: index }, () => {
    this.filterMatchList();
    });
  },

  // 处理成绩排名tab切换
  onResultTabChange(e) {
    console.log('onResultTabChange called', e);
    const index = e.currentTarget.dataset.index;
    console.log('index:', index);
    this.setData({ resultTabIndex: index }, () => {
      console.log('resultTabIndex updated to:', index);
    });
  },

  // 计算循环赛排名
  calculateRoundRobinResults() {
    const { matchList } = this.data;
    
    // 获取所有循环赛比赛
    const roundRobinMatches = matchList.filter(m => m.stage === 'RR');
    
    // 如果没有循环赛比赛，返回空数组
    if (roundRobinMatches.length === 0) {
      this.setData({ roundRobinResultList: [] });
      return;
    }
    
    // 统计所有搭档组成绩
    const comboMap = {};
    
    roundRobinMatches.forEach(match => {
      const leftKey = match.left.map(p => p.nickName).join('+');
      const rightKey = match.right.map(p => p.nickName).join('+');
      
      if (!comboMap[leftKey]) {
        comboMap[leftKey] = { 
          combo: match.left.slice(), 
          win: 0, 
          lose: 0,
          score: 0,
          players: match.left.map(p => p.nickName).join('+')
        };
      }
      if (!comboMap[rightKey]) {
        comboMap[rightKey] = { 
          combo: match.right.slice(), 
          win: 0, 
          lose: 0,
          score: 0,
          players: match.right.map(p => p.nickName).join('+')
        };
      }
      
      if (match.score && match.score.left !== undefined && match.score.right !== undefined) {
        if (match.score.left > match.score.right) {
          comboMap[leftKey].win += 1;
          comboMap[leftKey].score += match.score.left - match.score.right;
          comboMap[rightKey].lose += 1;
          comboMap[rightKey].score -= match.score.left - match.score.right;
        } else {
          comboMap[rightKey].win += 1;
          comboMap[rightKey].score += match.score.right - match.score.left;
          comboMap[leftKey].lose += 1;
          comboMap[leftKey].score -= match.score.right - match.score.left;
        }
      }
    });
    
    // 生成成绩数组
    const resultList = Object.values(comboMap).map((item, idx) => {
      const resultItem = {};
      // 复制item的所有属性
      for (let key in item) {
        if (item.hasOwnProperty(key)) {
          resultItem[key] = item[key];
        }
      }
      resultItem.idx = idx;
      return resultItem;
    });
    
    // 按胜场和净胜分排序
    resultList.sort((a, b) => {
      return b.win - a.win || b.score - a.score;
    });
    
    this.setData({ roundRobinResultList: resultList });
  }

});